package fun.xstar.controller;

import cn.hutool.json.JSONUtil;
import fun.xstar.model.WebhookMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Afan
 * @version 1.0 2023/11/21
 */
@Slf4j
@RestController
@RequestMapping("/ys7-demo")
public class WebhookController {
    @PostMapping(value = "/webhook")
    public ResponseEntity<String> webhook(@RequestHeader HttpHeaders header, @RequestBody String body) {
        final List<String> t = header.get("t");
        WebhookMessage receiveMessage = null;
        log.info("消息获取时间:{}, 请求头:{},请求体:{}", System.currentTimeMillis(), JSONUtil.toJsonStr(header), body);
        try {
            receiveMessage = JSONUtil.toBean(body, WebhookMessage.class);
            //todo:对收到的消息进行处理,最好发送到其他中间件,或者写到数据库中,不要影响回调地址的处理

        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
        }
        //必须进行返回
        Map<String, String> result = new HashMap<>(1);
        assert receiveMessage != null;
        String messageId = receiveMessage.getHeader().getMessageId();
        result.put("messageId", messageId);
        final ResponseEntity<String> resp = ResponseEntity.ok(JSONUtil.toJsonStr(result));
        log.info("返回的信息:{}", JSONUtil.toJsonStr(result));
        return resp;
    }

}
